package com.apes.fn.crm.ReturnVisit.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.crm.ReturnVisit.model.ReturnVisit;
import com.apes.fn.crm.ReturnVisit.model.VisitTransferHistory;
import com.apes.fn.crm.ReturnVisit.repository.ReturnVisitRepository;
import com.apes.fn.crm.ReturnVisit.repository.VisitTransferHistoryRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.party.model.PartyRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service("visitTransferHistoryService")
public class VisitTransferHistoryService extends DomainService {

    @Autowired
    VisitTransferHistoryRepository visitTransferHistoryRepository;
    @Autowired
    ReturnVisitRepository returnVisitRepository;

    /***
     * 创建
     */
    public VisitTransferHistory create(SimpleRequest request) {
        // 构建模型
        JSONObject tempJson = request.getJO();
        tempJson.remove("visitor");
        tempJson.remove("visitTransferHistoryItemsSelected");

        JSONArray array = tempJson.get("visitTransferHistoryItems") != null ?
                tempJson.getJSONArray("visitTransferHistoryItems") : new JSONArray();

        array =  array.stream().filter( obj -> {
            JSONObject json = (JSONObject) obj;
            if( json.get("preVisitor") == null ) return true;
            return json.get("visitor") != null && !json.getJSONObject("visitor").getString("id").equals(json.getJSONObject("preVisitor").getString("id"));
        }).map(obj -> {
            JSONObject json = (JSONObject) obj;
            return MapUtil.mapper(
                    "preVisitor", json.get("preVisitor") != null ? json.getJSONObject("preVisitor") : null,
                    "visitor", json.getJSONObject("visitor"),
                    "dept", json.getJSONObject("dept"),
                    "returnVisit", MapUtil.mapper(
                            "id", json.getJSONObject("returnVisit").getString("id")
                    ),
                    "state", json.getString("state")
            );
        }).collect(Collectors.toCollection(JSONArray::new));

        if (array.size() == 0) throw new RuntimeException("修改数量不能为0");

        tempJson.put("visitTransferHistoryItems", array);
        request.setData(tempJson);
        VisitTransferHistory visitTransferHistory = request.getO(VisitTransferHistory.class);
        visitTransferHistory.setTransferId(request.getPerson());
        visitTransferHistory.setTransferDate(new Date());
        visitTransferHistory.setCompany(request.getCurrentCompany());
        List<ReturnVisit> returnVisitList = new ArrayList();
        visitTransferHistory.getVisitTransferHistoryItems().forEach(visitTransferHistoryItem -> {

            ReturnVisit returnVisit = visitTransferHistoryItem.getReturnVisit();
            returnVisit.setVisitor(null);
            List<PartyRole> visitors = new ArrayList<>();
            visitors.add(visitTransferHistoryItem.getVisitor());
            returnVisit.setVisitors(visitors);
            returnVisitList.add(returnVisit);

        });
        returnVisitRepository.saveAll(returnVisitList);

        return visitTransferHistoryRepository.saveAndFlush(visitTransferHistory);
    }

//    /***
//     * 修改
//     */
//    public VisitTransferHistory update(SimpleRequest request) {
//        isValid(request, visitTransferHistoryRepository);
//        VisitTransferHistory visitTransferHistory = request.getO(VisitTransferHistory.class);
//        return visitTransferHistoryRepository.saveAndFlush(visitTransferHistory);
//    }
//
//    /***
//     * 删除
//     */
//    public String delete(SimpleRequest request) {
//        isValid(request, visitTransferHistoryRepository);
//        VisitTransferHistory visitTransferHistory = request.getO(VisitTransferHistory.class);
//        visitTransferHistoryRepository.delete(visitTransferHistory);
//        return "删除成功！";
//    }
//
//
//
//    /***
//     * 数据是否合法
//     * @param request
//     * @param repository
//     */
//    private Model isValid(SimpleRequest request, CustomRepository repository) {
//        Model oldModel = (Model) repository.findOne((String) request.get("id"));
//        if (oldModel == null) throw new RuntimeException("编码【" + request.get("id") + "】在系统中不存在。");
//        if (oldModel.getVersion() != (int) request.get("version")) throw new RuntimeException("记录已更新或已删除，请重新提交！");
//        return oldModel;
//    }
}
